package com.aiyige.page.interest.searchinterest;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.service.ApiService;
import com.aiyige.model.tag.Tag;
import com.aiyige.model.task.Task;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.model.NotifySearchInterestSelectedRequest;
import com.aiyige.page.interest.searchinterest.adapter.HistoryAdapter;
import com.aiyige.page.interest.searchinterest.adapter.SearchResultAdapter;
import com.aiyige.page.interest.searchinterest.model.HistoryResp;
import com.aiyige.page.interest.searchinterest.model.SearchData;
import com.aiyige.page.interest.searchinterest.model.SearchResp;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.LayoutMonitor;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TaskQueue.TaskQueue;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.SearchInterestPage)
public class SearchInterestPage extends AppCompatActivity {
    public static final String EXTRA_KEY_INTEREST_DATA = "com.aiyige.extra.EXTRA_KEY_INTEREST_DATA";
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.searchIcon)
    ImageView searchIcon;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;
    @BindView(R.id.mainRv)
    RecyclerView mainRv;
    HistoryAdapter historyAdapter;
    SearchResultAdapter searchResultAdapter;
    TaskQueue taskQueue;
    Handler mainHandler;
    @BindView(R.id.spaceLayout)
    ExpandableLayout spaceLayout;
    @BindView(R.id.titleBackContainer)
    ExpandableLayout titleBackContainer;

    TextView searchResultLabelTv;
    ImageView clearHistoryBtn;
    RecyclerView historyRv;
    LinearLayout historyLayout;
    View headerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_search_interest);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        historyAdapter = new HistoryAdapter();
        searchResultAdapter = new SearchResultAdapter();
        initHeader();
        historyRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        mainRv.setLayoutManager(new LinearLayoutManager(this));
        mainRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index == 0) {
                    outRect.set(0, 0, 0, 0);
                } else if (index == 1) {
                    outRect.set(UIHelper.dp2px(15), UIHelper.dp2px(13), UIHelper.dp2px(15), 0);
                } else {
                    outRect.set(UIHelper.dp2px(15), UIHelper.dp2px(8), UIHelper.dp2px(15), 0);
                }
            }
        });
        historyAdapter.bindToRecyclerView(historyRv);
        searchResultAdapter.bindToRecyclerView(mainRv);
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Interest interest = historyAdapter.getItem(position);
                nofitySearchInterestSelected(interest.getId(), interest.getTitle());
                doSelectInterest(interest);
            }
        });
        searchResultAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchData searchData = searchResultAdapter.getItem(position);
                switch (searchData.getType()) {
                    case SearchData.TYPE_ADD:
                        doAddInterest(searchData.getTitle());
                        break;
                    case SearchData.TYPE_NORMAL:
                        nofitySearchInterestSelected(searchData.getId(), searchData.getTitle());
                        doSelectInterest(Interest.newBuilder()
                                .id(searchData.getId())
                                .category(Interest.CATEGORY_INTEREST)
                                .type(Interest.TYPE_NORMAL)
                                .title(searchData.getTitle())
                                .sourceId(searchData.getSourceId())
                                .build());
                        break;
                }
            }
        });
        autoConfigSearchResultLabelTv();
        mainHandler = new Handler(Looper.getMainLooper());
        taskQueue = new TaskQueue("search interest thread");
        taskQueue.setCallback(new TaskQueue.Callback() {
            @Override
            public void handleTask(Object object) {
                try {
                    String keyword = object == null ? "" : (String) object;
                    final List<SearchData> result = new LinkedList<>();
                    if (!TextUtils.isEmpty(keyword)) {
                        Response<ResponseBody> resposne = ApiManager.getService().searchInterestByName(keyword).execute();
                        if (resposne.code() != ResponseCode.OK) {
                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(resposne));
                        }
                        String json = RetrofitUtil.getResponseBodyAsString(resposne);
                        List<SearchResp> searchRespList = JSON.parseArray(json, SearchResp.class);
                        for (SearchResp searchResp : searchRespList) {
                            result.add(SearchData.parse(searchResp));
                        }
                    }
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            searchResultAdapter.setNewData(result);
                            autoConfigSearchResultLabelTv();
                        }
                    });
                } catch (Exception e) {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            searchResultAdapter.setNewData(new LinkedList<SearchData>());
                            autoConfigSearchResultLabelTv();
                        }
                    });
                }
            }
        });
        taskQueue.onCreate();
        inputEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    inputEtClearBtn.setVisibility(View.INVISIBLE);
                    taskQueue.submitTask("");
                } else {
                    inputEtClearBtn.setVisibility(View.VISIBLE);
                    taskQueue.submitTask(s.toString());
                }
            }
        });
        inputEt.setFilters(new InputFilter[]{new InputNumFilter(15, true)});
        requestData();
        LayoutMonitor.newBuilder()
                .view(inputEt)
                .callback(new LayoutMonitor.Callback() {
                    @Override
                    public void onLayoutFinished() {
                        spaceLayout.collapse(false);
                        titleBackContainer.expand(false);
                    }
                })
                .once(true)
                .build()
                .install();
    }

    public void nofitySearchInterestSelected(String id, String title) {
        ApiManager.getService().notifySearchInterestSelected(NotifySearchInterestSelectedRequest.newBuilder()
                .avocationId(id)
                .name(title)
                .build())
                .enqueue(ApiManager.NOOP_CALLBACK);
    }

    public void initHeader() {
        headerView = LayoutInflater.from(this).inflate(R.layout.search_interest_page_header, (ViewGroup) mainRv.getParent(), false);
        searchResultAdapter.addHeaderView(headerView);
        searchResultLabelTv = headerView.findViewById(R.id.searchResultLabelTv);
        clearHistoryBtn = headerView.findViewById(R.id.clearHistoryBtn);
        historyRv = headerView.findViewById(R.id.historyRv);
        historyLayout = headerView.findViewById(R.id.historyLayout);
        clearHistoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClearHistory();
            }
        });
    }

    public void doSelectInterest(Interest interest) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_KEY_INTEREST_DATA, interest);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void doAddInterest(String title) {
        new AddInterestTask(this, title).execute();
    }

    public void requestData() {
        new RequestDataTask(this).execute();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        List<Interest> historyList = new LinkedList<>();

        public RequestDataTask(Activity activity) {
            super(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        public void safeOnPostExecute(Object o) {
            historyAdapter.setNewData(historyList);
            if (ListUtil.isEmpty(historyList)) {
                historyLayout.setVisibility(View.GONE);
            } else {
                historyLayout.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getHistoryInterest().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<HistoryResp> historyRespList = JSON.parseArray(json, HistoryResp.class);
                for (HistoryResp historyResp : historyRespList) {
                    historyList.add(Interest.newBuilder()
                            .id(historyResp.id)
                            .category(Interest.CATEGORY_INTEREST)
                            .type(Interest.TYPE_NORMAL)
                            .title(historyResp.name)
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    @Override
    protected void onDestroy() {
        taskQueue.onDestroy();
        super.onDestroy();
    }

    public void autoConfigSearchResultLabelTv() {
        if (searchResultAdapter.getData().isEmpty()) {
            searchResultLabelTv.setVisibility(View.INVISIBLE);
        } else {
            searchResultLabelTv.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.titleBackBtn, R.id.inputEtClearBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;

        }
    }

    public void doClearHistory() {
        new ClearHistoryTask(this).execute();
    }

    public class ClearHistoryTask extends SafeAsyncTask<Object, Object, Object> {

        public ClearHistoryTask(Activity activity) {
            super(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            historyAdapter.setNewData(new LinkedList<Interest>());
            historyLayout.setVisibility(View.GONE);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            //这里不需要任何操作
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .createTask(Task.newBuilder()
                                .name(Task.batchDeleteAllUserAvocationKeywords)
                                .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public class AddInterestTask extends SafeAsyncTask<Object, Object, Object> {
        String title;
        Interest createdInterest = null;

        public AddInterestTask(Activity activity, String title) {
            super(activity, R.string.text_process);
            this.title = title;
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                doSelectInterest(createdInterest);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().addInterest(InterestUtil.convertInterestToTag(Interest.newBuilder()
                        .title(title)
                        .type(Interest.TYPE_NORMAL)
                        .category(Interest.CATEGORY_INTEREST)
                        .build())).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Tag tag = JSON.parseObject(json, Tag.class);
                createdInterest = InterestUtil.convertTagToInterest(tag);
                if (createdInterest == null) {
                    throw new Exception(StringUtils.getString(R.string.create_interest_failed));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }
}
